<template>
  <div class="admin-layout">
    <!-- 左侧菜单 -->
    <div class="sidebar" :class="{ 'is-collapse': isCollapse }">
      <div class="logo-container">
        <el-icon size="32" color="#409EFF">
          <Trophy />
        </el-icon>
        <h2 v-show="!isCollapse" class="logo-title">运动会管理</h2>
      </div>
      
      <el-menu
        :default-active="activeMenu"
        :collapse="isCollapse"
        :unique-opened="true"
        router
        class="sidebar-menu"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
      >
        <!-- 首页 -->
        <el-menu-item index="/dashboard">
          <el-icon><House /></el-icon>
          <template #title>首页</template>
        </el-menu-item>

        <!-- 用户管理 - 只对管理员显示 -->
        <el-sub-menu index="user" v-if="isAdmin">
          <template #title>
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </template>
          <el-menu-item index="/user/list">用户列表</el-menu-item>
          <el-menu-item index="/role/list">角色管理</el-menu-item>
        </el-sub-menu>

        <!-- 人员管理 - 管理员和裁判可见 -->
        <el-sub-menu index="personnel" v-if="isAdmin || isJudge">
          <template #title>
            <el-icon><UserFilled /></el-icon>
            <span>人员管理</span>
          </template>
          <el-menu-item index="/athlete/list">运动员管理</el-menu-item>
          <el-menu-item index="/judge/list" v-if="isAdmin || isJudge">裁判员管理</el-menu-item>
        </el-sub-menu>

        <!-- 赛事管理 -->
        <el-sub-menu index="event">
          <template #title>
            <el-icon><Trophy /></el-icon>
            <span>赛事管理</span>
          </template>
          <!-- 比赛项目 - 管理员和裁判可见 -->
          <el-menu-item index="/event/list" v-if="isAdmin || isJudge">比赛项目</el-menu-item>
          <!-- 报名管理 - 管理员和运动员可见 -->
          <el-menu-item index="/registration/list" v-if="isAdmin || isAthlete">报名管理</el-menu-item>
          <!-- 报名审核 - 只有管理员可见 -->
          <el-menu-item index="/registration/audit" v-if="isAdmin">报名审核</el-menu-item>
          <!-- 赛事检录 - 管理员和裁判可见 -->
          <el-menu-item index="/event/checkin" v-if="isAdmin || isJudge">赛事检录</el-menu-item>
        </el-sub-menu>

        <!-- 成绩管理 -->
        <el-sub-menu index="score">
          <template #title>
            <el-icon><Medal /></el-icon>
            <span>成绩管理</span>
          </template>
          <!-- 成绩录入 - 管理员和裁判可见 -->
          <el-menu-item index="/score/entry" v-if="isAdmin || isJudge">成绩录入</el-menu-item>
          <!-- 成绩查询 - 所有人可见 -->
          <el-menu-item index="/score/query">成绩查询</el-menu-item>
          <!-- 排名统计 - 管理员和裁判可见 -->
          <el-menu-item index="/score/ranking" v-if="isAdmin || isJudge">排名统计</el-menu-item>
        </el-sub-menu>

        <!-- 统计分析 -->
        <!-- <el-sub-menu index="statistics" v-if="hasPermission('statistics')">
          <template #title>
            <el-icon><DataAnalysis /></el-icon>
            <span>统计分析</span>
          </template>
          <el-menu-item index="/statistics/overview">系统概览</el-menu-item>
          <el-menu-item index="/statistics/athlete">运动员统计</el-menu-item>
          <el-menu-item index="/statistics/event">项目统计</el-menu-item>
          <el-menu-item index="/statistics/team">团体统计</el-menu-item>
        </el-sub-menu> -->

        <!-- 公告管理 -->
        <el-menu-item index="/notice">
          <el-icon><Bell /></el-icon>
          <template #title>公告管理</template>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 主内容区 -->
    <div class="main-container" :class="{ 'is-collapse': isCollapse }">
      <!-- 顶部导航栏 -->
      <div class="navbar">
        <div class="navbar-left">
          <el-icon @click="toggleSidebar" class="hamburger">
            <Expand v-if="isCollapse" />
            <Fold v-else />
          </el-icon>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item v-if="currentBreadcrumb">{{ currentBreadcrumb }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        
        <div class="navbar-right">
          <el-dropdown @command="handleCommand">
            <span class="user-dropdown">
              <el-avatar :size="32" :src="userStore.userInfo?.avatar">
                {{ userStore.userInfo?.realName?.charAt(0) || 'U' }}
              </el-avatar>
              <span class="username">{{ userStore.userInfo?.realName || '用户' }}</span>
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                <el-dropdown-item command="password">修改密码</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="content-wrapper">
        <div class="app-main">
          <!-- 所有页面内容通过router-view显示 -->
          <router-view />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import {
  House, User, UserFilled, Trophy, Medal, DataAnalysis, Bell,
  Expand, Fold, ArrowDown, Plus, Edit
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 侧边栏折叠状态
const isCollapse = ref(false)

// 当前激活菜单
const activeMenu = computed(() => route.path)

// 面包屑
const currentBreadcrumb = computed(() => {
  const path = route.path
  const breadcrumbMap = {
    '/user/list': '用户列表',
    '/user/roles': '角色管理',
    '/athlete': '运动员管理',
    '/judge': '裁判员管理',
    '/event/list': '比赛项目',
    '/registration/list': '报名管理',
    '/registration/audit': '报名审核',
    '/event/checkin': '赛事检录',
    '/score/record': '成绩录入',
    '/score/query': '成绩查询',
    '/score/ranking': '排名统计',
    '/statistics/overview': '系统概览',
    '/statistics/athlete': '运动员统计',
    '/statistics/event': '项目统计',
    '/statistics/team': '团体统计',
    '/notice': '公告管理'
  }
  return breadcrumbMap[path] || ''
})

// 权限检查 - 取消权限认证，所有登录用户都可以访问
const hasPermission = (permission) => {
  // 直接返回 true，允许所有登录用户访问所有功能
  return true
}

// 判断是否为管理员
const isAdmin = computed(() => {
  // 检查用户名是否为admin，或者角色是否包含ADMIN
  return userStore.userInfo?.username === 'admin' || 
         userStore.roles.includes('ADMIN') || 
         userStore.roles.includes('admin')
})

// 判断是否为裁判
const isJudge = computed(() => {
  // 检查角色是否包含JUDGE，或者用户名是否以judge开头
  return userStore.roles.includes('JUDGE') || 
         userStore.roles.includes('judge') || 
         (userStore.userInfo?.username && userStore.userInfo.username.startsWith('judge'))
})

// 判断是否为运动员
const isAthlete = computed(() => {
  // 检查角色是否包含ATHLETE，或者用户名是否以athlete开头
  return userStore.roles.includes('ATHLETE') || 
         userStore.roles.includes('athlete') || 
         (userStore.userInfo?.username && userStore.userInfo.username.startsWith('athlete'))
})

// 切换侧边栏
const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

// 处理用户下拉菜单命令
const handleCommand = async (command) => {
  switch (command) {
    case 'profile':
      ElMessage.info('个人信息功能开发中...')
      break
    case 'password':
      ElMessage.info('修改密码功能开发中...')
      break
    case 'logout':
      await handleLogout()
      break
  }
}

// 处理退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await userStore.logout()
    ElMessage.success('退出登录成功')
  } catch (error) {
    if (error === 'cancel') {
      return
    }
    console.error('退出登录失败:', error)
  }
}

// 组件挂载时获取用户信息
onMounted(() => {
  if (!userStore.userInfo) {
    userStore.getUserInfo()
  }
})
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  display: flex;
}

/* 侧边栏样式 */
.sidebar {
  width: 210px;
  background-color: #304156;
  transition: width 0.3s;
  position: fixed;
  height: 100vh;
  left: 0;
  top: 0;
  z-index: 1001;
}

.sidebar.is-collapse {
  width: 64px;
}

.logo-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background-color: #2b2f3a;
}

.logo-title {
  color: #409EFF;
  margin: 0 0 0 10px;
  font-size: 18px;
  font-weight: bold;
}

.sidebar-menu {
  border: none;
  width: 100%;
}

/* 主容器样式 */
.main-container {
  flex: 1;
  margin-left: 210px;
  transition: margin-left 0.3s;
  display: flex;
  flex-direction: column;
}

.main-container.is-collapse {
  margin-left: 64px;
}

/* 顶部导航栏样式 */
.navbar {
  height: 60px;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  position: relative;
  z-index: 999;
}

.navbar-left {
  display: flex;
  align-items: center;
}

.hamburger {
  cursor: pointer;
  font-size: 20px;
  margin-right: 20px;
  color: #5a5e66;
}

.hamburger:hover {
  color: #409EFF;
}

.navbar-right {
  display: flex;
  align-items: center;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #5a5e66;
}

.username {
  margin: 0 8px;
}

/* 内容区域样式 */
.content-wrapper {
  flex: 1;
  overflow: hidden;
}

.app-main {
  height: calc(100vh - 60px);
  overflow-y: auto;
  background-color: #f0f2f5;
}

.dashboard-content {
  padding: 20px;
}

/* 仪表盘卡片样式 */
.dashboard-cards {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
}

.user-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.athlete-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.event-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.score-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

/* 图表区域样式 */
.dashboard-charts {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notice-list {
  max-height: 200px;
  overflow-y: auto;
}

.notice-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.notice-item:last-child {
  border-bottom: none;
}

.notice-title {
  color: #303133;
  cursor: pointer;
}

.notice-title:hover {
  color: #409EFF;
}

.notice-time {
  color: #909399;
  font-size: 12px;
}

.quick-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.quick-actions .el-button {
  flex: 1;
  min-width: 120px;
}

/* 用户信息样式 */
.user-info-section {
  margin-bottom: 20px;
}

.user-details p {
  margin-bottom: 8px;
  color: #606266;
  line-height: 1.6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    transform: translateX(-100%);
  }
  
  .sidebar.is-collapse {
    transform: translateX(0);
  }
  
  .main-container {
    margin-left: 0;
  }
  
  .dashboard-cards .el-col {
    margin-bottom: 20px;
  }
  
  .quick-actions .el-button {
    width: 100%;
    margin-bottom: 8px;
  }
}
</style>